package whitefox.gqtcard.dblocation;

import java.util.ArrayList;

import whitefox.gqtcard.MapActivity;
import whitefox.gqtcard.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SetLocations extends Activity {

	Button btnsave, btncancel;
	EditText id, name, note, et_x, et_y;
	Double x, y;
	ArrayList<whitefox.gqtcard.dblocation.Location> ListLocation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set_location);
		final DBLocation dbl = new DBLocation(this);
		ListLocation = new ArrayList<whitefox.gqtcard.dblocation.Location>();
		ListLocation = dbl.findall();
		id = (EditText) findViewById(R.id.et_ID);
		name = (EditText) findViewById(R.id.et_name);
		note = (EditText) findViewById(R.id.et_note);
		et_x = (EditText) findViewById(R.id.et_X);
		et_y = (EditText) findViewById(R.id.et_Y);
		Bundle bundle = getIntent().getExtras();
		x = bundle.getDouble("MyLatitude");
		y = bundle.getDouble("MyLongitude");
		et_x.setText(String.valueOf(x));
		et_y.setText(String.valueOf(y));

		btnsave = (Button) findViewById(R.id.buttonSave);
		btnsave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) 
			{
				whitefox.gqtcard.dblocation.Location myl = createlocation();
				if (myl !=null){
					if(dbl.createLocation(myl)){
						ListLocation.add(myl);
						Toast.makeText(getApplicationContext(), "update success", Toast.LENGTH_LONG).show();
						Intent intent = new Intent(SetLocations.this , MapActivity.class);
						startActivity(intent);
						
					}else
					{
						Toast.makeText(getApplicationContext(), "not edit", Toast.LENGTH_LONG).show();
					}
				}
				
			}
		});
		
		btncancel = (Button) findViewById(R.id.buttonCancel);
		btncancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public whitefox.gqtcard.dblocation.Location createlocation() {
		if (id.getText().length() == 0) {
			Toast.makeText(this, "ID is empty!", Toast.LENGTH_LONG).show();
			return null;
		}
		if (name.getText().length() == 0) {
			Toast.makeText(this, "Name is empty!", Toast.LENGTH_LONG).show();
			return null;
		}
		Location location = new Location(id.getText().toString(), name
				.getText().toString(), note.getText().toString(), x, y);
		return location;
	}
}
